<template>
    <div class="user-manage">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
            <div class="item-group">
                <el-form-item label="募捐项目ID:">
                    <el-input v-model="searchForm.fundraisingProjectsId" placeholder="请输入募捐项目ID" />
                </el-form-item>
                <el-form-item label="募捐项目名称:">
                    <el-input v-model="searchForm.fundraisingProjectsName" placeholder="请输入募捐项目名称" />
                </el-form-item>
            </div>
            <div class="btn-group">
                <el-button type="primary" @click="getFundraisingProjectsList" size="small">
                    <el-icon><Search /></el-icon>
                    搜索
                </el-button>
            </div>
        </el-form>
        <!-- 表格数据 -->
        <el-table 
            :data="tableData" 
            style="width: 100%" 
            border 
            :header-cell-style="{ background: 'rgb(216,231,246)' }" 
            max-height="500"
        >
            <el-table-column prop="fundraisingProjectsId" label="募捐项目ID" />
            <el-table-column prop="fundraisingProjectsName" label="募捐项目名称" />
            <el-table-column prop="expectedFundraisingAmount" label="期望募捐金额" />
            <el-table-column prop="totalAmount" label="已募集金额" />
            <el-table-column prop="usedAmount" label="已用金额" />
            <el-table-column label="操作" width="400">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleViewProcessingDetail(row)">查看处理明细</el-button>
                    <el-button link type="primary" @click="handleViewDonationDetail(row)">查看捐款明细</el-button>
                    <el-button link type="primary" @click="handleMoney(row)">处理捐款</el-button>
                    <el-button link type="primary" @click="handleViewComments(row)">查看评论</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next,jumper"
                :page-sizes="[10, 50, 100]"
                :total="total"
                v-model:page-size="pageSize"
                v-model:current-page="currentPage"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <!-- 查看处理明细弹窗 -->
        <el-dialog v-model="processingDialogVisible" width="700" title="捐款处理明细">
            <el-table 
                :data="processingInfo" 
                style="width: 100%" 
                :header-cell-style="{ background: 'rgb(216,231,246)' }" 
                max-height="500"
            >
                <el-table-column prop="donationProcessingId" label="捐款处理ID" />
                <el-table-column prop="amountUsed" label="使用金额" />
                <el-table-column prop="useDestination" label="使用目的" />
                <el-table-column prop="useTime" label="使用时间" />
                <el-table-column prop="useCertificate" label="使用凭证">
                    <template #default="scope">
                        <el-image :src="imageUrl + scope.row.useCertificate" style="width: 50px; height: 50px" />
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- 查看捐款明细弹窗 -->
        <el-dialog v-model="donationDialogVisible" width="700" title="捐款来源明细">
            <el-table 
                :data="donationInfo" 
                style="width: 100%" 
                :header-cell-style="{ background: 'rgb(216,231,246)' }" 
                max-height="500"
            >
                <el-table-column prop="donationRecordsId" label="捐款记录ID" />
                <el-table-column prop="donationAmount" label="捐赠金额" />
                <el-table-column prop="donatorUsername" label="捐款人" />
                <el-table-column prop="donationTime" label="捐赠时间" :formatter="handleFormatDate" />
            </el-table>
        </el-dialog>
        <!-- 处理捐款弹窗 -->
        <el-dialog v-model="moneyDialogVisible" width="500" title="处理捐款">
            <el-form :model="dialogForm">
                <el-form-item label="使用金额:" prop="amountUsed">
                    <el-input v-model="dialogForm.amountUsed" placeholder="请输入使用金额（不得超过募捐金额）" type="number" :max="maxAmount" :min="0" @blur="handleBlur" />
                </el-form-item>
                <el-form-item label="使用去向:" prop="useDestination">
                    <el-input v-model="dialogForm.useDestination" type="textarea" placeholder="请输入使用目的" :autosize="{ minRows: 4, maxRows: 4 }" />
                </el-form-item>
                <el-form-item label="使用凭证" prop="useCertificate">
                    <el-upload
                        ref="upload"
                        class="avatar-uploader"
                        :action="fileUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :on-error="handleAvatarError"
                        :before-upload="beforeAvatarUpload"
                        :limit="1"
                    >
                        <el-image v-if="dialogForm.useCertificate" :src="imageUrl + dialogForm.useCertificate" style="width: 100px; height: 100px;" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="handleSure">确定</el-button>
                <el-button @click="moneyDialogVisible = false">取消</el-button>
            </template>
        </el-dialog>
        <!-- 查看评论弹窗 -->
        <el-dialog v-model="commentsDialogVisible" width="700" title="评论">
            <el-table 
                :data="commentsInfo" 
                style="width: 100%" 
                :header-cell-style="{ background: 'rgb(216,231,246)' }" 
                max-height="500"
            >
                <el-table-column prop="donatorUsername" label="捐赠者" width="100" />
                <el-table-column prop="commentContent" label="评论内容" />
                <el-table-column prop="commentTime" label="评论时间" :formatter="handleFormatDate" width="200" />
            </el-table>
        </el-dialog>
    </div>
</template>
  
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { adminApi, agencyApi, donatorApi } from '../../api/app';
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, UploadInstance, UploadProps } from 'element-plus';
import { dayjs } from 'element-plus';
import { fileUrl, imageUrl } from '../../api/request';
import { handleFormatDate, beforeAvatarUpload, handleAvatarError } from './ts/common';

/** 当前登录用户的募捐机构ID */
const { agencyId } = JSON.parse(localStorage.getItem('user') || "");
/** 搜索表单 */
const searchForm = ref({
    fundraisingProjectsId: null,
    fundraisingProjectsName: null
})
/** 表格数据 */
const tableData = ref([])
/** 数据总数 */
const total = ref(0);
/** 当前页码 */
const currentPage = ref(1);
/** 每页显示条数 */
const pageSize = ref(10);
/** 查看处理明细弹窗可见性 */
const processingDialogVisible = ref(false);
/** 查看捐款明细弹窗可见性 */
const donationDialogVisible = ref(false);
/** 处理捐款弹窗可见性 */
const moneyDialogVisible = ref(false);
/** 查看评论弹窗可见性 */
const commentsDialogVisible = ref(false);
/** 处理明细信息列表 */
const processingInfo = ref([]);
/** 捐款明细信息列表 */
const donationInfo = ref([]);
/** 评论信息列表 */
const commentsInfo = ref([]);
/** 处理捐款弹窗表单 */
const dialogForm = ref({
    fundraisingProjectsId: null,
    agencyId: null,
    amountUsed: 0,
    useDestination: null,
    useCertificate: null,
});
/** 可以使用的最大金额 */
const maxAmount = ref(0);
const upload = ref<UploadInstance>();
  
// 初始加载
onMounted(() => {
    // 获取募捐项目列表
    getFundraisingProjectsList();
});
  
/** 获取募捐项目信息列表 */
const getFundraisingProjectsList = () => {
    agencyApi.getFundraisingProjectsAndMoney({ 
        pageNum: currentPage.value, 
        pageSize: pageSize.value,
        agencyId: agencyId,
        ...searchForm.value,
    }).then((res: any) => {
        if (res) {
            tableData.value = res.records;
            total.value = res.total;
        }
    });
};

/** 查看处理明细 */
const handleViewProcessingDetail = (row: any) => {
    agencyApi.getDonationProcessingRecords({ fundraisingProjectsId: row.fundraisingProjectsId }).then((res: any) => {
        if (res) {
            processingInfo.value = res.records;
        }
    })
    processingDialogVisible.value = true;
}

/** 查看捐款明细 */
const handleViewDonationDetail = (row: any) => {
    agencyApi.getDonationRecords({ fundraisingProjectsId: row.fundraisingProjectsId }).then((res: any) => {
        if (res) {
            donationInfo.value = res;
        }
    })
    donationDialogVisible.value = true;
}

/** 处理捐款 */
const handleMoney = (row: any) => {
    maxAmount.value = row.totalAmount - row.usedAmount;
    dialogForm.value = {
        ...dialogForm.value, 
         fundraisingProjectsId: row.fundraisingProjectsId,
         agencyId: agencyId
    }
    moneyDialogVisible.value = true;
}

/** 重置弹窗内容并关闭弹窗 */
const resetDialog = () => {
    dialogForm.value = {
        fundraisingProjectsId: null,
        agencyId: null,
        amountUsed: 0,
        useDestination: null,
        useCertificate: null,
    };
    moneyDialogVisible.value = false;
};
  
/** 弹窗确定 */
const handleSure = () => {
    if (dialogForm.value.amountUsed === 0) {
        ElMessage.error('请输入使用金额');
        return;
    }
    agencyApi.addDonationProcessing(dialogForm.value).then(res => {      
        if (res) {
            ElMessage.success('处理成功');
            moneyDialogVisible.value = false;
            resetDialog();
            getFundraisingProjectsList();
        } else {
            ElMessage.error('处理失败');
        }
    })
};

/** 弹窗输入框失去焦点 */
const handleBlur = () => {
    // 输入金额不能超过募捐金额 同时不能小于 0
    if (dialogForm.value.amountUsed > maxAmount.value) {
        dialogForm.value.amountUsed = maxAmount.value;
    }
    if (dialogForm.value.amountUsed < 0) {
        dialogForm.value.amountUsed = 0;
    }
};
  
/** 表格分页大小改变 */
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    getFundraisingProjectsList();
}
  
/** 表格页码改变 */
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    getFundraisingProjectsList();
};

/** 查看评论 */
const handleViewComments = (row: any) => {
    donatorApi.getCommentByFundraisingProjectsId({ fundraisingProjectsId: row.fundraisingProjectsId }).then((res: any) => {
        if (res) {
            commentsInfo.value = res;
        }
    })
    commentsDialogVisible.value = true;
}

/** 上传头像成功 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (res: any) => {
    dialogForm.value.useCertificate = res;
    upload.value!.clearFiles(); // 清除已上传文件
};
</script>
  
<style lang="less">
@import "./css/tableForm.less";
</style>